package org.example.controller;

import org.example.domain.User;
import org.example.repository.UserRepository;
import org.example.util.PasswordUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

//@CrossOrigin(origins = "http://localhost:8081")
@RestController
@RequestMapping("/test")
public class TestController {

    @Autowired
    private UserRepository userRepository;

    @GetMapping("/test01")
    public void test01(){
        String encode = PasswordUtils.encode(new StringBuilder("123456"));
    }

    @PostMapping("/addUser")
    public User addUser(@RequestBody User user) {
        return userRepository.save(user);
    }

    @GetMapping("/getAllUsers")
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    @PutMapping("/updateUser/{id}")
    public User updateUser(@PathVariable String id, @RequestBody User user) {
        Optional<User> optionalUser = userRepository.findById(Long.valueOf(id));
        if (optionalUser.isPresent()) {
            User existingUser = optionalUser.get();
            existingUser.setUsername(user.getUsername()); // 使用username字段
            return userRepository.save(existingUser);
        }
        return null;
    }

    @DeleteMapping("/deleteUser/{id}")
    public void deleteUser(@PathVariable String id) {
        userRepository.deleteById(Long.valueOf(id));
    }
}
